package com.wali.modules.system.control;

import com.wali.common.ccp.exception.CcpException;
import com.wali.common.ccp.execl.CcpExcelUtils;
import com.wali.common.ccp.secret.CcpSecretManager;
import com.wali.common.enums.ErrorCodeEnum;
import com.wali.common.web.BaseController;
import com.wali.modules.system.bo.SysUserBO;
import com.wali.modules.system.enums.UserCodeEnum;
import com.wali.modules.system.service.SysUserService;
import com.wali.modules.system.vo.Area;
import com.wali.modules.system.vo.SysUserVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.*;


/**
 * @ClassName: LoginController
 * @Description: 登录controller类
 * @author: wali
 * @email wali.xu@kpmg.com
 * @date: 11/11/2018 11:01 上午
 */
@Controller
public class LoginController extends BaseController {

    @Autowired
    private SysUserService sysUserService;

    /***
     * 跳转到系统入口页
     *
     * @return String
     */
    @RequestMapping(value = {"/"}, method = RequestMethod.GET)
    public String index() {
        return "index";
    }

    /**
     * @Title: login
     * @Description: 登录
     * @param: request
     * @return: ResponseEntity
     * @throws:
     */
    @RequestMapping(value = "/login")
    public ResponseEntity<String> login(HttpServletRequest request) {
        int code = ErrorCodeEnum.ERROR_INTERNAL_CODE.getCode();
        String msg = ErrorCodeEnum.ERROR_INTERNAL_CODE.getMessage();

        logger.info("login in");

        try {
            String username = request.getParameter("username");
            String password = request.getParameter("password");

            SysUserBO sysUser = new SysUserBO();
            sysUser.setUsername(username);
            sysUser.setPassword(password);

            checkUserIsNull(sysUser);// 校验用户信息是否为空
            SysUserVO sysUserVO = checkUserPwdIsError(sysUser);// 校验用户密码是否正确

            HttpSession session = request.getSession(true);
            String token = CcpSecretManager.getInstance().encryptMD5(String.valueOf(new Date().getTime()));
            session.setAttribute("access_token", token);
            session.setAttribute("username", sysUserVO.getUsername());
            session.setAttribute("user", sysUserVO);

            Map<String, String> data = new HashMap<>();
            data.put("access_token", token);
            data.put("index", sysUserVO.getHome());
            code = ErrorCodeEnum.SUCCESS_CODE.getCode();

            return getResponseEntity(code, data);
        } catch (CcpException e) {
            logger.error(e.getMessage(), e);
            code = e.getException().getCode();
            msg = e.getException().getMessage();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }

        return getResponseEntity(code, msg);
    }

    /**
     * @Title: logout
     * @Description: 登出
     * @param:
     * @return: ResponseEntity
     * @throws:
     */
    @RequestMapping(value = "/logout")
    public ResponseEntity<String> logout(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if (session != null) {
            session.invalidate();
        }

        return getResponseEntity(ErrorCodeEnum.SUCCESS_CODE.getCode());
    }

    /**
     * @param
     * @return
     * @throws
     * @Title
     * @Description 校验是否超时了
     */
    @RequestMapping(value = "/checkIsTimeout")
    public ResponseEntity<String> checkIsTimeout() {
        return getResponseEntity(ErrorCodeEnum.SUCCESS_CODE.getCode());
    }

    /**
     * @param
     * @return
     * @throws
     * @Title
     * @Description 注册用户
     */
    @RequestMapping(value = "/regUser")
    public ResponseEntity<String> regUser(HttpServletRequest request) {
        int code = ErrorCodeEnum.ERROR_INTERNAL_CODE.getCode();
        String msg = ErrorCodeEnum.ERROR_INTERNAL_CODE.getMessage();

        try {
            SysUserBO sysUserBO = getObjectFromReq(request, SysUserBO.class);

            checkConfirmPassword(sysUserBO);// 校验确认密码是否一致
            checkUsernameExist(sysUserBO);// 确认用户名是否已经存在

            int result = sysUserService.regSysUser(sysUserBO);// 注册用户
            code = ErrorCodeEnum.SUCCESS_CODE.getCode();
            msg = ErrorCodeEnum.SUCCESS_CODE.getMessage();
        } catch (CcpException e) {
            logger.error(e.getMessage(), e);
            code = e.getException().getCode();
            msg = e.getException().getMessage();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }

        return getResponseEntity(code, msg);
    }


    @Autowired
    private JdbcTemplate template;

    @RequestMapping(value = "importArea")
    public ResponseEntity<String> importArea(HttpServletRequest request) {
        int code = ErrorCodeEnum.ERROR_INTERNAL_CODE.getCode();
        String msg = ErrorCodeEnum.ERROR_INTERNAL_CODE.getMessage();

        try {
            template.execute("truncate com_area");

            String path = "C://" + File.separator + "Users" + File.separator + "walixu" + File.separator + "Desktop" + File.separator + "123.xlsx";
            File file = new File(path);

            CcpExcelUtils ccpExcelUtils = new CcpExcelUtils(file, 0, 1);
            final List<Area> dataList = ccpExcelUtils.getDataList(Area.class);
            Iterator<Area> iterator = dataList.iterator();
            while (iterator.hasNext()) {
                Area next = iterator.next();

                if (next.getCode().endsWith("0000")) {
                    next.setParentCode("CN");
                } else {
                    next.setParentCode(next.getCode().substring(0, 2) + "0000");
                }
            }

            CcpExcelUtils ccpExcelUtils2 = new CcpExcelUtils(file, 0, 0);
            List<Area> dataList2 = ccpExcelUtils2.getDataList(Area.class);
            Iterator<Area> iterator3 = dataList2.iterator();
            while (iterator3.hasNext()) {
                Area next = iterator3.next();

                if (next.getCode().endsWith("0000")) {
                    next.setParentCode("CN");
                } else {
                    if (next.getCode().endsWith("00")) {
                        next.setParentCode(next.getCode().substring(0, 2) + "0000");
                    } else {
                        next.setParentCode(next.getCode().substring(0, 4) + "00");
                    }
                }
            }

            dataList.addAll(dataList2);


            String[] delete = new String[]{"市辖区", "县"};
            Iterator<Area> iterator4 = dataList.iterator();
            while (iterator4.hasNext()) {
                Area next = iterator4.next();
                if (Arrays.asList(delete).contains(next.getName())) {
                    iterator4.remove();
                }
            }

            StringBuilder sql = new StringBuilder();
            sql.append("insert into com_area (code, parent_code, name, postcode, sort, create_time, update_time) ");
            sql.append("values (?, ?, ?, ?, ?, now(), now())");

            template.batchUpdate(sql.toString(), new BatchPreparedStatementSetter() {
                @Override
                public void setValues(PreparedStatement ps, int i) throws SQLException {
                    Area area = dataList.get(i);

                    ps.setString(1, area.getCode());
                    ps.setString(2, area.getParentCode());
                    ps.setString(3, area.getName());
                    ps.setString(4, area.getPostcode());
                    ps.setInt(5, area.getSort());
                }

                @Override
                public int getBatchSize() {
                    return dataList.size();
                }
            });

            code = ErrorCodeEnum.SUCCESS_CODE.getCode();
            msg = ErrorCodeEnum.SUCCESS_CODE.getMessage();
        } catch (CcpException e) {
            logger.error(e.getMessage(), e);
            code = e.getException().getCode();
            msg = e.getException().getMessage();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }

        return getResponseEntity(code, msg);
    }

    /**
     * @param sysUser
     * @return
     * @throws
     * @Title checkUserIsNull
     * @Description 校验用户名、密码是否为空
     */

    private void checkUserIsNull(SysUserBO sysUser) {
        if (StringUtils.isBlank(sysUser.getUsername())) {
            throw new CcpException(UserCodeEnum.USERNAME_CANNOT_EMPTY);
        }
        if (StringUtils.isBlank(sysUser.getPassword())) {
            throw new CcpException(UserCodeEnum.PASSWORD_CANNOT_EMPTY);
        }
    }

    /**
     * @param
     * @return
     * @throws
     * @Title checkUserPwdIsError
     * @Description 校验用户密码是否错误
     */
    private SysUserVO checkUserPwdIsError(SysUserBO sysUser) {
        SysUserVO result = sysUserService.getSysUser(sysUser);
        if (result == null) {
            throw new CcpException(UserCodeEnum.LOGIN_CODE_PASSWORD_ERROR);
        }

        return result;
    }

    /**
     * @param
     * @return
     * @throws
     * @Title checkConfirmPassword
     * @Description 校验确认密码是否一致
     */
    private void checkConfirmPassword(SysUserBO sysUser) {
        if (StringUtils.isBlank(sysUser.getPassword()) || StringUtils.isBlank(sysUser.getConfirmPassword())) {
            throw new CcpException(UserCodeEnum.PASSWORD_CANNOT_EMPTY);
        }

        if (!sysUser.getPassword().equals(sysUser.getConfirmPassword())) {
            throw new CcpException(UserCodeEnum.ERROR_CONFIRM_PASSWORD);
        }
    }

    /**
     * @param
     * @return
     * @throws
     * @Title checkUsernameExist
     * @Description 校验用户名是否已经存在
     */
    private void checkUsernameExist(SysUserBO sysUser) {
        if (StringUtils.isBlank(sysUser.getUsername())) {
            throw new CcpException(UserCodeEnum.USERNAME_CANNOT_EMPTY);
        }

        boolean exist = sysUserService.checkSysUserExist(sysUser.getUsername());
        if (exist) {
            throw new CcpException(UserCodeEnum.ERROR_USERNAME_EXIST);
        }
    }
}
